import java.io.*
import java.util.*
import kotlin.test.assertEquals

/**
 * 重定向输入流，从文件中读入流
 */
fun <T : Any> redirectSystemIn(clazz: Class<T>, action: () -> Unit) {
    redirectSystemIn(clazz, null, action)
}

/**
 * 重定向输入流，从文件中读入流
 * @param testCaseIndex 要使用的TestCase索引值
 */
fun <T : Any> redirectSystemIn(clazz: Class<T>, testCaseIndex: Int?, action: () -> Unit) {
    val filename = if (testCaseIndex == null) "/${clazz.simpleName}.txt" else "/${clazz.simpleName}/$testCaseIndex.txt"
    System.setIn(clazz.javaClass.getResourceAsStream(filename))
    action()
}

/**
 * 重定向输出流
 */
fun redirectSystemOut(action: (expected: MutableList<String>) -> Unit) {
    val stream = ByteArrayOutputStream()
    val pStream = PrintStream(stream)
    val origin = System.out
    System.setOut(pStream)
    val expectedList = mutableListOf<String>()
    action(expectedList)

    System.setOut(origin)
    val inStream = ByteArrayInputStream(stream.toByteArray())
    val reader = BufferedReader(InputStreamReader(inStream))

    val lines = reader.readLines().map { it.trim() }
    val iterator = lines.iterator()
    for (expected in expectedList) {
        println(expected)
        assertEquals(expected, iterator.next())
    }
}